package com.edais.service.imp;

import com.edais.dao.WeixinEnjoyDao;
import com.edais.service.WeixinEnjoyService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.Message;
import com.edais.vo.InvestVo;
import com.edais.vo.LoanLenderVo;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service

public class WeixinEnjoyServiceImpl implements WeixinEnjoyService {

	private static final Log logger = LogFactory
			.getLog(WeixinEnjoyServiceImpl.class);
	@Autowired
	private WeixinEnjoyDao weixinEnjoyDao;

	@Override
	public ResultDTO getInvestList(Map<String, Object> map) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
        int pageSize = Integer.parseInt(String.valueOf(map.get("pageSize")));
		ResultDTO result = null;
		String todayInvestNum = "0";
		int totalSize = weixinEnjoyDao.getInvestListSize(map);
		if (totalSize <= 0) {

            result = new ResultDTO(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(),
                    ResultCode.SUCCESS.getType(),pageSize, 0, new ArrayList());
            return result;
		}
		List<InvestVo> investTempList = weixinEnjoyDao.getInvestList(map);
		result = new ResultDTO(ResultCode.SUCCESS);
		result.setRecords(investTempList);
		/**
		 * 调用核心接口 E390018
		 * */
		String transCode = "E390018";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		String jsonStr = CommonUtil.constructJsonStr(transCode,
				null+ "", queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if (Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))) {
			todayInvestNum = jsonObject.getString("totalNum");
			JSONObject json = new JSONObject();
			json.put("todayInvestNum",todayInvestNum);
			result.setRecord(json);
		}

//		List<Map<String, String>> investBannerList = weixinEnjoyDao.getInvestBannerList();
//		String investBanner = "";
//
//		if (null != investBannerList && investBannerList.size() > 0) {
//			investBanner = investBannerList.get(0).get("FTP_PATH");
//		}
//		logger.info("获取投资理财banner:"+investBanner);
//		resultMap.put("list", investList);
//		resultMap.put("totalNum", totalSize);
//		resultMap.put("listSize", investList.size());
//		resultMap.put("investBanner", investBanner);
//
//		result = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),
//				ResultCode.SUCCESS.getType(),totalSize,investBannerList);
//
//		logger.info("---------------------/wxenjoy/getInvestList WeixinEnjoyServiceImpl getInvestList.size()"
//				+ investList.size() + "--------------------------");
//
//		return result;

		return result;
	}

	@Override
	public Map<String, Object> enjoyPlanProductIndex(Map<String, Object> map)
			throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		/**
		 * 调用核心接口 E390001
		 * */
		String transCode = "E390001";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		queryCoreMap.put("userId", map.get("userId"));
		queryCoreMap.put("productId", map.get("productId"));
		String jsonStr = CommonUtil.constructJsonStr(transCode,
				map.get("userId") + "", queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if (Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))) {
			JSONObject jsonArr = jsonObject.getJSONObject("indexDetail");
			String[] keys={
					"returnRate",
					"totalAssets",
					"curBondAmount",
					"matchAmount",
					"inAmount",
					"outAmount",
					"yesterdayYield",
					"yesterdayIncome",
					"totalIncome",
					"todayInvestNum",
					"incomeDay",
					"isShow",
					"isInvest"
			};
			if(jsonArr != null && jsonArr.size() > 0){
				for (int i = 0; i < keys.length; i++) {
					if(jsonArr.containsKey(keys[i])){
						rtnMap.put(keys[i], jsonArr.getString(keys[i]));
					}else{
						rtnMap.put(keys[i], "");
					}
				}
			}else{
				for (int i = 0; i < keys.length; i++) {
					rtnMap.put(keys[i], "0");
				}
			}
		}
		return rtnMap;

	}

	@Override
	public ResultDTO queryEnjoyTodayUserInfoList(Map<String, Object> map) throws Exception {

		ResultDTO result;
		List<LoanLenderVo> loanLenderVoList = new ArrayList<LoanLenderVo>();
		String transCode = "E390009";
		Map<String, Object> coreMap = new HashMap<String, Object>();
		String current = map.get("currentPage") + "";
		String pageSize = map.get("pageSize") + "";
		int totlePages = 0;
		coreMap.put("pageSize", pageSize);
		coreMap.put("current", current);
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		if (Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))) {
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if (jsonArr != null && jsonArr.size() > 0) {
				for (int i = 0; i < jsonArr.size(); i++) {
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					LoanLenderVo loanLenderVo = new LoanLenderVo();
					String realName = jsonObj.getString("realName");
					if (null != realName && !"".equals(realName) && realName.length() > 1) {
						// *处理
						int nameLength = realName.length();
						String endStar = "*";
						/* for (int a = 1; a < nameLength; a++) {
							 endStar += "*";
						 }*/
						if (nameLength>2){
							realName = realName.substring(0, 1) + endStar+realName.substring(nameLength-1, nameLength);
						}else{
							realName = realName.substring(0, 1) + endStar;
						}
					}
					loanLenderVo.setRealName(realName);
					loanLenderVo.setImageIconDispose(jsonObj
							.getString("imageIconDispose"));
					loanLenderVo.setBuyDate(jsonObj.getString("buyDate"));
					loanLenderVoList.add(loanLenderVo);
				}

				result = new ResultDTO(ResultCode.SUCCESS);
				result.setPageSize(Integer.parseInt(pageSize));
				result.setTotal(Integer.parseInt(jsonObject.getString("totalNum")));
				result.setRecords(loanLenderVoList);
			} else {
				result = new ResultDTO(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), ResultCode.SUCCESS.getType(),
						Integer.parseInt(pageSize), Integer.parseInt(jsonObject.getString("totalNum")), new ArrayList());
			}

		} else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode")
					+ "；  resmsg：" + jsonObject.getString("resmsg"));
			result = new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}

		return  result;
	}

	@Override
	public String saveOrUpdateIosDeviceInfo(Map<String, Object> paramMap)
			throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = "";
		try {
			weixinEnjoyDao.saveOrUpdateIosDeviceInfo(paramMap);
		} catch (Exception e) {
			result = CommonUtil.setResultStringCn(resultMap, Consts.CHECK_CODE,
					"", "保存或修改ios设备信息");
			return result;
		}
		result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE,
				"", "");

		logger.info("---------------------/wxenjoy/saveIosDeviceInfo WeixinEnjoyServiceImpl");

		return result;
	}
	/**
	 * 优享计划详情(网站)
	 */
	@Override
	public Map<String, Object> getEnjoyPlanDetail(Map<String, String> map) throws Exception{
		return weixinEnjoyDao.getEnjoyPlanDetail(map);
	}

	@Override
	public String querySysTime() throws Exception {
		return weixinEnjoyDao.querySysTime();
	}

}